<?php
header("content-Type: text/html; charset=Utf-8"); 
error_reporting(0);
require($_SERVER['DOCUMENT_ROOT']."/config.php");
$con = mysql_connect($spConfig["db"]["host"], $spConfig["db"]["login"], $spConfig["db"]["password"]);
$db_selected = mysql_select_db($spConfig["db"]["database"],$con);
define("con", $con);
define("TOKEN", "myxfbilnn2017");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
//$wechatObj->valid();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {    
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){ 
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $type= $postObj->MsgType;
                if ($type=="text"){
                    $time = time();
                    $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";             
				    if(!empty( $keyword ) || $keyword=="0")
                    {
              		$msgType = "text";
              		$contentStr = "您好，欢迎您的加入！";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                    }else{
                	echo "Input something...";
                    }
                }
                if ($type=="event"){
                $Event= $postObj->Event;
                if ($Event=="subscribe"){
                	$data = $postObj->EventKey;
                	$data = str_replace("qrscene_", "", $data);
                	$aid = 0;
                	$bid = 0;
                	if (!empty($data)){
                		$result = mysql_query("Select id,bid from user where state=0 and id=".$data,con);
                		$row=mysql_fetch_row($result);
                		if (!empty($row)){
                          $aid = $row[1];
                          $bid = $row[0];
                		}
                	}
                	$updata['aid'] = $aid;
                	$updata['bid'] = $bid;
                	$updata['username'] = $fromUsername;
                	$result = mysql_query("Select id from user where username='".$updata['username']."'",con);
                    $row=mysql_fetch_row($result);
                    if (empty($row)){
                        mysql_query("Insert into user(username,aid,bid,times)values('".$updata['username']."',".$updata['aid'].",".$updata['bid'].",".time().")");
                    }
                    $time = time();
                    $msgType = "text";
                    $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";
                    $contentStr = "您好，欢迎您的加入！";        
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }
        }
        }else {
        	echo "";
        	exit;
        }
    }
	private function checkMobile($mobilephone){
     if(preg_match("/^13[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$mobilephone)){ 
     return true;
     }else{
     return false;
     } 
    }	
    private function checkdh($mobilephone){
        return true;
    }   
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}
?>